import { useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { AuthContext } from '@/contexts/authContext';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';

// 用户信息接口
interface UserData {
  username: string;
  avatar?: string;
  email?: string;
  phone?: string;
  campus: string;
  bio?: string;
  joinDate: string;
  transactions: number;
  rating: number;
}

// 模拟用户数据
const mockUserData: UserData = {
  username: 'student1',
  avatar: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=male%20college%20student%20avatar&sign=ce2e40061e9899bed92d3bab0ea79407',
  email: 'student1@example.com',
  phone: '138****1234',
  campus: '主校区',
  bio: '热爱编程和摄影的大学生',
  joinDate: '2023-09-01',
  transactions: 12,
  rating: 4.8
};

// 收货地址接口
interface Address {
  id: string;
  name: string;
  phone: string;
  campus: string;
  detail: string;
  isDefault: boolean;
}

// 模拟地址数据
const mockAddresses: Address[] = [
  {
    id: '1',
    name: '张三',
    phone: '138****1234',
    campus: '主校区',
    detail: '学生公寓A栋501室',
    isDefault: true
  },
  {
    id: '2',
    name: '张三',
    phone: '138****1234',
    campus: '东校区',
    detail: '图书馆3楼自习室',
    isDefault: false
  }
];

export default function UserProfile() {
  const [userData, setUserData] = useState<UserData>(mockUserData);
  const [addresses, setAddresses] = useState<Address[]>(mockAddresses);
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState<UserData>(mockUserData);
  const [isLoading, setIsLoading] = useState(false);
  const { logout, userInfo } = useContext(AuthContext);
  const navigate = useNavigate();
  const { theme } = useTheme();

  // 编辑模式切换
  const toggleEdit = () => {
    if (isEditing) {
      // 取消编辑，重置表单
      setEditForm({ ...userData });
    }
    setIsEditing(!isEditing);
  };

  // 表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setEditForm(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 保存用户信息
  const saveUserInfo = async () => {
    setIsLoading(true);
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setUserData(editForm);
      setIsEditing(false);
      toast.success('个人信息已更新');
    } catch (error) {
      toast.error('更新失败，请稍后重试');
      console.error('更新用户信息时出错:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 设置默认地址
  const setDefaultAddress = (addressId: string) => {
    const updatedAddresses = addresses.map(address => ({
      ...address,
      isDefault: address.id === addressId
    }));
    setAddresses(updatedAddresses);
    toast.success('默认地址已设置');
  };

  // 删除地址
  const deleteAddress = (addressId: string) => {
    if (addresses.find(a => a.id === addressId)?.isDefault) {
      toast.warning('默认地址不能删除，请先设置其他地址为默认');
      return;
    }
    
    if (window.confirm('确定要删除该地址吗？')) {
      const updatedAddresses = addresses.filter(address => address.id !== addressId);
      setAddresses(updatedAddresses);
      toast.success('地址已删除');
    }
  };

  // 处理退出登录
  const handleLogout = () => {
    if (window.confirm('确定要退出登录吗？')) {
      logout();
      navigate('/login');
    }
  };

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900 py-8 px-4 sm:px-6 lg:px-8")}>
      <div className="max-w-4xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">个人中心</h1>
          <button
            onClick={handleLogout}
            className="text-sm text-red-600 dark:text-red-400 hover:text-red-500 dark:hover:text-red-300"
          >
            <i className="fa-solid fa-right-from-bracket mr-1"></i>
            退出登录
          </button>
        </div>
        
        {/* 用户基本信息 */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6 mb-6">
          <div className="flex flex-col md:flex-row md:items-center">
            {/* 用户头像 */}
            <div className="flex-shrink-0 mb-4 md:mb-0">
              <div className="w-24 h-24 rounded-full bg-gray-100 dark:bg-gray-700 overflow-hidden">
                {userData.avatar ? (
                  <img 
                    src={userData.avatar} 
                    alt={userData.username}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center">
                    <i className="fa-solid fa-user text-4xl text-gray-400"></i>
                  </div>
                )}
              </div>
            </div>
            
            {/* 用户信息 */}
            <div className="md:ml-6 flex-1">
              <div className="flex flex-col md:flex-row md:items-center justify-between">
                <div>
                  <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-1">
                    {isEditing ? (
                      <input
                        type="text"
                        name="username"
                        value={editForm.username}
                        onChange={handleInputChange}
                        className="w-40 px-2 py-1 border-b border-gray-300 dark:border-gray-600 bg-transparent text-gray-900 dark:text-white focus:outline-none focus:border-indigo-500"
                      />
                    ) : (
                      userData.username
                    )}
                  </h2>
                  <div className="flex items-center text-sm text-gray-500 dark:text-gray-400">
                    <span className="flex items-center">
                      <i className="fa-solid fa-location-dot mr-1"></i>
                      {userData.campus}
                    </span>
                    <span className="mx-2">·</span>
                    <span>注册于 {userData.joinDate}</span>
                  </div>
                </div>
                
                {/* 操作按钮 */}
                {isEditing ? (
                  <div className="mt-3 md:mt-0 flex space-x-2">
                    <button
                      onClick={saveUserInfo}
                      disabled={isLoading}
                      className={`px-4 py-1.5 rounded-lg text-sm font-medium ${
                        isLoading 
                          ? 'bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 cursor-not-allowed' 
                          : 'bg-indigo-600 dark:bg-indigo-500 text-white hover:bg-indigo-700 dark:hover:bg-indigo-600'
                      }`}
                    >
                      {isLoading ? (
                        <><i className="fa-solid fa-circle-notch fa-spin mr-1"></i>
                          保存中...
                        </>
                      ) : (
                        <>
                          <i className="fa-solid fa-check mr-1"></i>
                          保存
                        </>
                      )}
                    </button>
                    <button
                      onClick={toggleEdit}
                      disabled={isLoading}
                      className="px-4 py-1.5 rounded-lg text-sm font-medium border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
                    >
                      <i className="fa-solid fa-times mr-1"></i>
                      取消
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={toggleEdit}
                    className="mt-3 md:mt-0 px-4 py-1.5 rounded-lg text-sm font-medium border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700"
                  >
                    <i className="fa-solid fa-pen-to-square mr-1"></i>
                    编辑资料
                  </button>
                )}
              </div>
              
              {/* 个人简介 */}
              <div className="mt-4">
                {isEditing ? (
                  <textarea
                    name="bio"
                    value={editForm.bio || ''}
                    onChange={handleInputChange}
                    placeholder="介绍一下自己吧"
                    rows={2}
                    className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  />
                ) : userData.bio ? (
                  <p className="text-sm text-gray-700 dark:text-gray-300">{userData.bio}</p>
                ) : (
                  <p className="text-sm text-gray-500 dark:text-gray-400">暂无个人介绍</p>
                )}
              </div>
            </div>
          </div>
        </div>
        
        {/* 账户信息 */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6 mb-6">
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4">账户信息</h3>
          
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <div className="w-10 h-10 flex-shrink-0 bg-indigo-100 dark:bg-indigo-900 rounded-full flex items-center justify-center mr-4">
                  <i className="fa-solid fa-envelope text-indigo-600 dark:text-indigo-400"></i>
                </div>
                <span className="text-sm text-gray-700 dark:text-gray-300">邮箱</span>
              </div>
              {isEditing ? (
                <input
                  type="email"
                  name="email"
                  value={editForm.email || ''}
                  onChange={handleInputChange}
                  className="w-64 px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm"
                />
              ) : (
                <span className="text-sm text-gray-900 dark:text-white">{userData.email || '未设置'}</span>
              )}
            </div>
            
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <div className="w-10 h-10 flex-shrink-0 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mr-4">
                  <i className="fa-solid fa-phone text-green-600 dark:text-green-400"></i>
                </div>
                <span className="text-sm text-gray-700 dark:text-gray-300">手机号码</span>
              </div>
              {isEditing ? (
                <input
                  type="tel"
                  name="phone"
                  value={editForm.phone || ''}
                  onChange={handleInputChange}
                  className="w-64 px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm"
                />
              ) : (
                <span className="text-sm text-gray-900 dark:text-white">{userData.phone || '未设置'}</span>
              )}
            </div>
            
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <div className="w-10 h-10 flex-shrink-0 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center mr-4">
                  <i className="fa-solid fa-location-dot text-blue-600 dark:text-blue-400"></i>
                </div>
                <span className="text-sm text-gray-700 dark:text-gray-300">校区</span>
              </div>
              {isEditing ? (
                <select
                  name="campus"
                  value={editForm.campus}
                  onChange={handleInputChange}
                  className="w-64 px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm"
                >
                  <option value="主校区">主校区</option>
                  <option value="东校区">东校区</option>
                  <option value="西校区">西校区</option>
                  <option value="南校区">南校区</option>
                  <option value="北校区">北校区</option>
                </select>
              ) : (
                <span className="text-sm text-gray-900 dark:text-white">{userData.campus}</span>
              )}
            </div>
          </div>
        </div>
        
        {/* 交易信息 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4">交易记录</h3>
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <div className="w-10 h-10 flex-shrink-0 bg-purple-100 dark:bg-purple-900 rounded-full flex items-center justify-center mr-4">
                  <i className="fa-solid fa-shopping-bag text-purple-600 dark:text-purple-400"></i>
                </div>
                <div>
                  <div className="text-sm text-gray-700 dark:text-gray-300">成功交易</div>
                  <div className="text-2xl font-bold text-gray-900 dark:text-white">{userData.transactions}</div>
                </div>
              </div>
              <div className="flex items-center">
                <div className="w-10 h-10 flex-shrink-0 bg-yellow-100 dark:bg-yellow-900 rounded-full flex items-center justify-center mr-4">
                  <i className="fa-solid fa-star text-yellow-600 dark:text-yellow-400"></i>
                </div>
                <div>
                  <div className="text-sm text-gray-700 dark:text-gray-300">信用评分</div>
                  <div className="text-2xl font-bold text-gray-900 dark:text-white">{userData.rating}</div>
                </div>
              </div>
            </div>
          </div>
          
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4">安全设置</h3>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <div className="w-10 h-10 flex-shrink-0 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center mr-4">
                    <i className="fa-solid fa-key text-red-600 dark:text-red-400"></i>
                  </div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">修改密码</span>
                </div>
                <button className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-300">
                  <i className="fa-solid fa-chevron-right"></i>
                </button>
              </div>
              
              <div className="flex items-center justify-between">
                <div className="flex items-center">
                  <div className="w-10 h-10 flex-shrink-0 bg-orange-100 dark:bg-orange-900 rounded-full flex items-center justify-center mr-4">
                    <i className="fa-solid fa-shield-alt text-orange-600 dark:text-orange-400"></i>
                  </div>
                  <span className="text-sm text-gray-700 dark:text-gray-300">账号安全</span>
                </div>
                <button className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-300">
                  <i className="fa-solid fa-chevron-right"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        
        {/* 收货地址 */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold text-gray-900 dark:text-white">收货地址</h3>
            <button className="px-4 py-1.5 rounded-lg text-sm font-medium border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              <i className="fa-solid fa-plus mr-1"></i>
              添加地址
            </button>
          </div>
          
          <div className="space-y-4">
            {addresses.map((address) => (
              <div 
                key={address.id} 
                className="p-4 border border-gray-200 dark:border-gray-700 rounded-xl hover:border-indigo-300 dark:hover:border-indigo-700 transition-colors"
              >
                <div className="flex flex-wrap items-start justify-between">
                  <div>
                    <div className="flex items-center">
                      <span className="text-sm font-medium text-gray-900 dark:text-white">{address.name}</span>
                      <span className="text-sm text-gray-500 dark:text-gray-400 ml-3">{address.phone}</span>
                      {address.isDefault && (
                        <span className="ml-2 text-xs text-white bg-indigo-600 dark:bg-indigo-500 px-2 py-0.5 rounded-full">默认</span>
                      )}
                    </div>
                    <div className="mt-2 text-sm text-gray-700 dark:text-gray-300">
                      {address.campus} {address.detail}
                    </div>
                  </div>
                  
                  <div className="mt-2 sm:mt-0 flex space-x-2">
                    {!address.isDefault && (
                      <button
                        onClick={() => setDefaultAddress(address.id)}
                        className="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
                      >
                        设为默认
                      </button>
                    )}
                    <button className="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700">
                      编辑
                    </button>
                    <button
                      onClick={() => deleteAddress(address.id)}
                      className="px-3 py-1 text-xs border border-red-300 dark:border-red-700 text-red-600 dark:text-red-400 rounded hover:bg-red-50 dark:hover:bg-red-900/20"
                    >
                      删除
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}